﻿using System;
using System.Web;
using System.Web.UI;
using gms.data;
using gms.security;
using gms.system;

namespace gms.page {
	public class login : GMSPage {
		public string message = "";

		public login() {
			this.Load += new EventHandler(login_Load);
		}

		void login_Load(object sender, EventArgs e) {
			bool posted = false;
			string email = "";
			string password = "";

			if (Request.Form.Count != 0) {
				posted = true;
			}
			else {
				if (Authentication.IsSessionAuthed()) {
					Authentication.ClearSession();
				}
			}

			if (posted) {
				if (Request.Form["email"] != null) {
					if (Request.Form["email"].Length != 0) {
						email = Request.Form["email"];
					}
					else {
						posted = false;
						message = "You must enter an Email!";
					}
				}
				else {
					posted = false;
					message = "You must enter an Email!";
				}

				if (Request.Form["password"] != null) {
					if (Request.Form["password"].Length != 0) {
						password = Request.Form["password"];
					}
					else {
						posted = false;
						message = "You must enter a Password!";
					}
				}
				else {
					posted = false;
					message = "You must enter a Password!";
				}
			}

			if (posted) {
				if (Authentication.IsValidLogin(email, password)) {
					Player loginee = Player.load_by_email(email);
					Authentication.AuthedPlayer = loginee.player_id;

					nhdb.session.BeginTransaction();
					loginee.address = Authentication.AuthedIP;
					nhdb.session.Update(loginee);
					nhdb.session.Transaction.Commit();
				}
				else {
					posted = false;
					message = "Invalid email and password combination!";
				}
			}

			if (posted) {
				Response.Redirect("/default.aspx");
			}
		}
	}
}